package likou.offer;

import java.util.Arrays;

/**
 * @Info:
 * @Author: 唐小尊
 * @Date: 2020/8/14  22:37
 */
public class _21 {
    public static void main(String[] args) {
        int nums[] = {1, 2, 3, 4};
        System.out.println(Arrays.toString(exchange(nums)));
    }

    public static int[] exchange(int[] nums) {
        int nowJi = 0;//遇到偶数后，当前遍历到的最后一个奇数的下标
        for (int i = 0; i < nums.length - 1; i++) {
            if (nums[i] % 2 == 0) {
                if (nowJi < i) {
                    nowJi = i + 1;
                }
                while (nowJi < nums.length && nums[nowJi] % 2 == 0) {
                    nowJi++;
                }
                if (nowJi < nums.length) {
                    int temp = nums[i];
                    nums[i] = nums[nowJi];
                    nums[nowJi] = temp;
                    nowJi++;
                }
                //当前后面没有奇数
                if (nowJi == nums.length) {
                    break;
                }
            }
        }
        return nums;
    }
    public int[] exchange2(int[] nums) {
        int left = 0;
        int right = nums.length-1;
        while(right>left){
            //找偶数
            while(left<nums.length&&nums[left]%2==1){
                left++;
            }
            //找奇数
            while(right>0&&nums[right]%2==0){
                right--;
            }
            if(left>right){
                break;
            }else{
                int temp = nums[left];
                nums[left] = nums[right];
                nums[right] = temp;
                left++;
                right--;
            }
        }
        return nums;
    }
}
